﻿using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;

using GrimorioApplication.Model;
using System;

namespace GrimorioApplication.ViewModel
{
    public class GrimorioViewModel : INotifyPropertyChanged
    {
        #region INotifyPropertyChanged Members

        public event PropertyChangedEventHandler PropertyChanged;

        // Used to notify Silverlight that a property has changed;
        private void NotifyPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
        #endregion

        public GrimorioDataContext GrimorioDB;

        public GrimorioViewModel(string GrimorioDBConnectionString)
        {
            GrimorioDB = new GrimorioDataContext(GrimorioDBConnectionString);
        }

        public void SaveChangesToDB()
        {
            GrimorioDB.SubmitChanges();
        }

        private ObservableCollection<DataRecipe> _allRecipes;
        public ObservableCollection<DataRecipe> AllRecipes
        {
            get { return _allRecipes; }
            set
            {
                _allRecipes = value;
                NotifyPropertyChanged("AllRecipes");
            }
        }

        private ObservableCollection<RecipeIngredients> _allRecipeToIng;
        public ObservableCollection<RecipeIngredients> AllRecipeToIng
        {
            get { return _allRecipeToIng; }
            set
            {
                _allRecipeToIng = value;
                NotifyPropertyChanged("AllRecipeToIng");
            }
        }

        private ObservableCollection<Ingredients> _allIngredients;
        public ObservableCollection<Ingredients> AllIngredients
        {
            get { return _allIngredients; }
            set
            {
                _allIngredients = value;
                NotifyPropertyChanged("AllIngredients");
            }
        }

        public void LoadCollectionsFromDatabase()
        {
            var RecipeInDB = from DataRecipe rt in GrimorioDB.RecipesT
                             select rt;
            var RecipeToIngInDB = from RecipeIngredients rti in GrimorioDB.RecipeToIngT
                                  select rti;
            var IngredientsInDB = from Ingredients i in GrimorioDB.IngredientsT
                                  select i;

            AllRecipes = new ObservableCollection<DataRecipe>(RecipeInDB);
            AllRecipeToIng = new ObservableCollection<RecipeIngredients>(RecipeToIngInDB);
            AllIngredients = new ObservableCollection<Ingredients>(IngredientsInDB);
        }

        //ADD LOGIC
        public void AddRecipe(DataRecipe newRecipe)
        {
            // Add a new recipe  to the data context.
            GrimorioDB.RecipesT.InsertOnSubmit(newRecipe);
            // Save changes to the database.
            GrimorioDB.SubmitChanges();
            // Add a new recipe to the "all" observable collection.
            AllRecipes.Add(newRecipe);
        }

        public void AddRecipeToIng(RecipeIngredients newRecipeToIng)
        {
            // Add a new RecipeToIng  to the data context.
            GrimorioDB.RecipeToIngT.InsertOnSubmit(newRecipeToIng);
            // Save changes to the database.
            GrimorioDB.SubmitChanges();
            // Add a new RecipeToIng to the "all" observable collection.
            AllRecipeToIng.Add(newRecipeToIng);
        }

        public void AddIngredient(Ingredients newIngredient)
        {
            // Add a new Ingredient  to the data context.
            GrimorioDB.IngredientsT.InsertOnSubmit(newIngredient);
            // Save changes to the database.
            GrimorioDB.SubmitChanges();
            // Add a new Ingredient to the "all" observable collection.
            AllIngredients.Add(newIngredient);
        }

        //REMOVE LOGIC
        public void DeleteRecipe(DataRecipe forDelete)
        {
            //while (forDelete.IngredientsQuantity.Count() > 0)
            //    DeleteRecipeToIng(forDelete.IngredientsQuantity.FirstOrDefault());
            while (forDelete.IngredientsQuantity.Count > 0)
            {
                DeleteRecipeToIng(forDelete.IngredientsQuantity.FirstOrDefault());
            }
            AllRecipes.Remove(forDelete);
            GrimorioDB.RecipesT.DeleteOnSubmit(forDelete);
            GrimorioDB.SubmitChanges();
        }

        public void DeleteRecipeToIng(RecipeIngredients forDelete)
        {
            AllRecipeToIng.Remove(forDelete);
            GrimorioDB.RecipeToIngT.DeleteOnSubmit(forDelete);
            GrimorioDB.SubmitChanges();
        }

        public void DeleteIngredient(Ingredients forDelete)
        {

            //while (forDelete.RecipeQuantity.Count > 0)
            //    DeleteRecipeToIng(forDelete.RecipeQuantity.FirstOrDefault());

            AllIngredients.Remove(forDelete);
            GrimorioDB.IngredientsT.DeleteOnSubmit(forDelete);
            GrimorioDB.SubmitChanges();
        }

        private List<int> _ingredientIdList;
        public List<int> getIngredientIdList()
        {
            _ingredientIdList = (from Ingredients ing in GrimorioDB.IngredientsT
                                 select ing.IngredientsID).ToList();
            return _ingredientIdList;
        }

        private Ingredients _ingWithId;
        public Ingredients getIngredientWithID(int ID)
        {
            var x = from Ingredients ing in GrimorioDB.IngredientsT
                    where ing.IngredientsID == ID
                    select ing;
            _ingWithId = x.FirstOrDefault();
            return _ingWithId;
        }

        public int getIdRecipeWithDefaultName()
        {
            var x = from DataRecipe dr in GrimorioDB.RecipesT
                    where dr.RecipeName == "Grimorio_TeMpOrArY_Recipe"
                    select dr.RecipeId;
            return x.FirstOrDefault();
        }


        public string getQuantityOfIngredient(int indexOfIngredient)
        {
            var quantity = (from RecipeIngredients ingr in GrimorioDB.RecipeToIngT
                            where ingr.Ingredient.IngredientsID == indexOfIngredient
                            select ingr.Quantity).ToString();
            return quantity;
        }

        public int getIngredientIdFromName(string nameOfIngredient)
        {
            var query = (from RecipeIngredients ing in GrimorioDB.RecipeToIngT
                         where ing.Ingredient.IngredientName == nameOfIngredient
                         select ing._ingredientID).ToString();
            return Convert.ToInt32(query);
        }

        public List<IngredientsAndQuantity> getIngredientsAndQuantityOfRecipeSelected(int idOfRecipe)
        {
            List<IngredientsAndQuantity> listToReturn = new List<IngredientsAndQuantity>();

            var query = (from RecipeIngredients ri in GrimorioDB.RecipeToIngT
                         where ri._recipeID == idOfRecipe
                         select ri).ToList();


            foreach (RecipeIngredients recipeingr in query)
            {
                IngredientsAndQuantity addToList = new IngredientsAndQuantity()
                {
                    ingredientName = recipeingr.Ingredient.IngredientName,
                    ingredientQuantity = recipeingr.Quantity.ToString()
                };
                listToReturn.Add(addToList);
            }

            return listToReturn;
        }

        public List<RecipeIngredients> recipeIngredientsOfSelectedRecipe(int idOfRecipe)
        {
            var query = (from RecipeIngredients ri in GrimorioDB.RecipeToIngT
                         where ri._recipeID == idOfRecipe
                         select ri).ToList();
            return query;
        }

        public DataRecipe getRecipeWithSelectedId(int index)
        {
            var query = (from DataRecipe dr in GrimorioDB.RecipesT
                         where dr.RecipeId == index
                         select dr).FirstOrDefault();
            return query;
        }

        /// <summary>
        /// Search from database recipes that starts with "startWith"
        /// </summary>
        /// <param name="startWith">word starts with string</param>
        /// <returns>List</returns>
        public List<DataRecipe> getRecipeListBeginWith(string startWith)
        {
            var x = from DataRecipe recipe in GrimorioDB.RecipesT
                    where recipe.RecipeName.StartsWith(startWith)
                    orderby recipe.RecipeName ascending
                    select recipe;
            return x.ToList();
        }
        
        /// <summary>
        /// Search from database recipes that starts with "startWith" & have property = dish_difficulty string, type = 0 for dish, type !0 for difficulty
        /// </summary>
        /// <param name="startWith">word starts with string</param>
        /// <param name="dish_difficulty">dish or difficulty list item</param>
        /// <param name="type">0 for dish, !0 for difficulty</param>
        /// <returns>List</returns>
        public List<DataRecipe> getRecipeListBeginWith(string startWith, string dish_difficulty, int type)
        {
            if (type == 0)
            {
                var x = from DataRecipe recipe in GrimorioDB.RecipesT
                    where recipe.RecipeName.StartsWith(startWith) && recipe.Dish == dish_difficulty
                    orderby recipe.RecipeName ascending
                    select recipe;
                return x.ToList();
            }
            else
            {
                var x = from DataRecipe recipe in GrimorioDB.RecipesT
                    where recipe.RecipeName.StartsWith(startWith) && recipe.Difficulty == dish_difficulty
                    orderby recipe.RecipeName ascending
                    select recipe;
                return x.ToList();
            }
            
        }

        /// <summary>
        /// Search from database recipes that starts with "startWith" & both dish & difficulty set
        /// </summary>
        /// <param name="startWith">word starts with string</param>
        /// <param name="difficulty">difficulty list item</param>
        /// <param name="dish">dish list item</param>
        /// <returns>List</returns>
        public List<DataRecipe> getRecipeListBeginWith(string startWith, string difficulty, string dish)
        {
            var x = from DataRecipe recipe in GrimorioDB.RecipesT
                    where recipe.RecipeName.StartsWith(startWith) && recipe.Difficulty == difficulty && recipe.Dish == dish
                    orderby recipe.RecipeName ascending
                    select recipe;
            return x.ToList();
        }
    }

    public class IngredientsAndQuantity
    {
        public string ingredientName { get; set; }
        public string ingredientQuantity { get; set; }
    }

}



//DataRecipe
//     int RecipeId
//     string RecipeName
//     string Dish
//     Boolean IsVegetarian
//     string Difficulty
//     string Stars
//     string TimeForPreparation
//     string Description
//     string NumberOfPeople
//     string Matchings
//     byte[] Image

//     EntitySet<RecipeIngredients> IngredientsQuantity

//RecipeIngredients
//     int RecipeIngredientsID
//     string Quantity

//     DataRecipe Recipe
//     Ingredients Ingredient

//Ingredients
//     int IngredientsID
//     string IngredientName

//     EntitySet<RecipeIngredients> IngredientsQuantity
